package com.huangyi.ack.config;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitTemplateConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMandatory(true); // 开启强制消息路由
        template.setConfirmCallback((correlation, ack, reason) -> {
            if (!ack) {
                System.err.println("Message failed: " + reason);
            }
        });
        return template;
    }
    @Bean
    public RabbitTemplate confirmRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                System.out.println("Confirm 生产端发送成功" );
                if(b){
                    System.out.printf("Exchange 接收到消息 ，消息ID: %s \n" , correlationData == null? null : correlationData.getId());
                }else {
                    System.out.printf("Exchange 未接收到消息，消息ID:%s ， cause: %s\n",correlationData == null? null : correlationData.getId()
                            ,s);
                }
            }
        });
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.printf("消息被退回：%s",returnedMessage);
            }
        });
        return rabbitTemplate;
    }

    @Bean
    public RabbitTemplate returnRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.printf("消息被退回：%s",returnedMessage);
            }
        });
        return rabbitTemplate;
    }
}
